<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
<script>
  {
    // 广度优先
    function treeToArray(tree){
      const queue = [...tree]
      const arr = []
      let current = queue.shift()
      while (current){
        if (current.children){
          queue.push(...current.children)
          delete current.children
        }
        arr.push(current)
        current = queue.shift()
      }
      return arr
    }

    const listTree = [
      {
        id: 1,
        name: '部门1',
        pid: 0,
        children: [
          {
            id: 2,
            name: '部门1-1',
            pid: 1,
            children: [
              {
                id: 4,
                name: '部门1-1-1',
                pid: 2,
                children: []
              }
            ]
          },
          {
            id: 3,
            name: '部门1-2',
            pid: 1,
            children: [
              {
                id: 5,
                name: '部门1-2-1',
                pid: 3,
                children: []
              }
            ]
          }
        ]
      },
      {
        id: 6,
        name: '部门2',
        pid: 0,
        children: [
          {
            id: 7,
            name: '部门2-1',
            pid: 6,
            children: []
          }
        ]
      },
      {
        id: 8,
        name: '部门3',
        pid: 0,
        children: []
      }
    ]
    console.log(treeToArray(listTree))
  }
  {
    // 深度优先
    function treeToArray(tree){
      const arr = []
      tree.forEach(item => {
        arr.push(item)
        if (item.children){
          arr.push(...treeToArray(item.children))
          delete item.children
        }
      })
      return arr
    }
    const listTree = [
      {
        id: 1,
        name: '部门1',
        pid: 0,
        children: [
          {
            id: 2,
            name: '部门1-1',
            pid: 1,
            children: [
              {
                id: 4,
                name: '部门1-1-1',
                pid: 2,
                children: []
              }
            ]
          },
          {
            id: 3,
            name: '部门1-2',
            pid: 1,
            children: [
              {
                id: 5,
                name: '部门1-2-1',
                pid: 3,
                children: []
              }
            ]
          }
        ]
      },
      {
        id: 6,
        name: '部门2',
        pid: 0,
        children: [
          {
            id: 7,
            name: '部门2-1',
            pid: 6,
            children: []
          }
        ]
      },
      {
        id: 8,
        name: '部门3',
        pid: 0,
        children: []
      }
    ]
    console.log(treeToArray(listTree))
  }
</script>
</html>